<html>
<head>

<title>Groovy Goodness: Create New Date or Calendar from Existing and Set Property Value</title>

<script language="javascript" src="scripts/shCore.js"></script> 
<script language="javascript" src="scripts/shLegacy.js"></script> 
<script language="javascript" src="scripts/shBrushJava.js"></script> 
<script language="javascript" src="scripts/shBrushXml.js"></script> 
<script language="javascript" src="scripts/shBrushJScript.js"></script> 
<script language="javascript" src="scripts/shBrushGroovy.js"></script> 
<script language="javascript" src="scripts/shBrushPlain.js"></script> 
<script language="javascript" src="scripts/shBrushBash.js"></script> 
 
<link href="styles/reset.css" rel="stylesheet" type="text/css" />
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link type="text/css" rel="stylesheet" href="styles/shThemeRDark.css"/>
<link href="styles/blog.css" rel="stylesheet" type="text/css" />

</head>
<body>

<a href="index.html">Back to index</a>

<h3 class="post-title">Groovy Goodness: Create New Date or Calendar from Existing and Set Property Value</h3>

<div class="post">
<p>Since Groovy 2.2 we can create a new <code>Date</code> or <code>Calendar</code> object from an existing <code>Date</code> and <code>Calendar</code> object and directly change property values. We must use the <code>copyWith()</code> method and we pass a map with property names and values as an argument. The newly created object will have the old values for properties from the original object and the properties set in the map are overridden.</p><p>The following code shows the new <code>copyWith()</code> method:</p><pre class="brush:groovy">import static java.util.Calendar.NOVEMBER

// Create original date.
def date = new Date().clearTime()
date.set(year: 2013, month: NOVEMBER, date: 18)

// Use copyWith to get new Date and 
// immmediatelly set year to 2014.
def yearLater = date.copyWith(year: 2014)

assert yearLater.format('dd-MM-yyyy') == '18-11-2014'


// Also works for Calendar.
def cal = Calendar.instance
cal.set(year: 2013, month: NOVEMBER, date: 10)

// Create new Calendar with new date value.
def newCalendar = cal.copyWith(date: 18)

assert newCalendar.format('dd-MM-yyyy') == '18-11-2013'
</pre><p>Code written with Groovy 2.2.</p
</div>

<script language="javascript"> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'scripts/clipboard.swf';
SyntaxHighlighter.defaults['first-line'] = 0;
SyntaxHighlighter.defaults['auto-links'] = false;
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

</body>
</html>